package com.quad.innovators.salesease.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quad.innovators.salesease.mapper.SysUserRoleMapper;
import com.quad.innovators.salesease.model.bo.UserRoleBO;
import com.quad.innovators.salesease.model.entity.SysUserRole;
import com.quad.innovators.salesease.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveUserRoles(String userCode, List<String> roleCodes) {

        if (userCode == null || CollectionUtil.isEmpty(roleCodes)) {
            return false;
        }

        // 用户原角色ID集合
        List<String> userRoleCodes = this.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserCode, userCode))
                .stream().map(SysUserRole::getRoleCode).collect(Collectors.toList());

        // 新增用户角色
        List<String> saveRoleIds;
        if (CollectionUtil.isEmpty(userRoleCodes)) {
            saveRoleIds = roleCodes;
        } else {
            saveRoleIds = roleCodes.stream().filter(roleId -> !userRoleCodes.contains(roleId)).collect(Collectors.toList());
        }

        List<SysUserRole> saveUserRoles = saveRoleIds
                .stream()
                .map(roleCode -> new SysUserRole(userCode, roleCode))
                .collect(Collectors.toList());
        this.saveBatch(saveUserRoles);

        // 删除用户角色
        if (CollectionUtil.isNotEmpty(userRoleCodes)) {
            List<String> removeRoleIds = userRoleCodes.stream()
                    .filter(roleId -> !roleCodes.contains(roleId))
                    .collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(removeRoleIds)) {
                this.remove(new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserCode, userCode)
                        .in(SysUserRole::getRoleCode, removeRoleIds)
                );
            }
        }
        return true;

    }


    @Override
    public boolean hasAssignedUsers(String roleCode) {
        int count = this.baseMapper.countUsersForRole(roleCode);
        return count > 0;
    }

    @Override
    public List<UserRoleBO> selectRoleByUserIds(List<String> userCodeList) {
        if(CollectionUtil.isEmpty(userCodeList)){
            return new ArrayList<>();
        }
        return this.baseMapper.selectRoleByUserIds(userCodeList);
    }
}
